import java.util.Arrays;

public class myPriorityQueue {
    public int[] elem;
    public int usedSize;

    public static int DEFAULT_SIZE = 16;

    public myPriorityQueue() {
        elem = new int[DEFAULT_SIZE];//默认创建大小为16的优先级队列
    }

    /**
     * 建堆的时间复杂度：O(NLogN)
     * 默认小顶堆
     *
     * @param array
     */
    public void createHeap(int[] array) {
        while (array.length > elem.length) {
            elem = Arrays.copyOf(elem, elem.length << 1);
        }
        elem = Arrays.copyOf(array, elem.length);
        usedSize = array.length;
        for (int parent = (usedSize - 1 - 1) >> 1; parent >= 0; parent--) {
            shiftDown(parent, usedSize);//左闭右开
        }
    }

    /**
     * @param parent 是每棵子树的根节点的下标
     * @param len    是每棵子树调整结束的结束条件
     *               向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int parent, int len) {
        int child = parent << 1 + 1;
        while (child < len) {
            if (child + 1 < len && elem[child + 1] < elem[child])
                child++;//转移到右孩子处
            if (elem[parent] > elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent = child;
                child = parent << 1 + 1;
            } else {
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     *
     * @param val
     */
    public void push(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, elem.length << 1);
        }
        //插到堆尾，然后向上调整
        elem[usedSize] = val;
        //向上调整
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        //找到父节点
        int parent = (child - 1) >> 1;
        while (child > 0) {
            if (elem[parent] < elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) >> 1;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是小根堆
     */
    public void pollHeap() {
        if(isEmpty()){
            return;
        }
        swap(elem,0,usedSize--);
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     *
     * @return
     */
    public int peekHeap() {
        return elem[0];
    }

    //交换
    public void swap(int[] a,int i,int j){
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}